'use client';

export const dynamic = 'force-dynamic';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-client';
import {
  BookOpen,
  Target,
  Trophy,
  Clock,
  TrendingUp,
  Star,
  Play,
  Settings,
  LogOut,
  Shield,
  AlertCircle
} from 'lucide-react';

interface UserProfile {
  id: number;
  username: string;
  email?: string;
  displayName: string;
  role: string;
}

interface LearningStats {
  totalTopicsLearned: number;
  totalQuestionsAnswered: number;
  correctAnswers: number;
  currentStreak: number;
  totalStudyTime: number;
}

export default function Dashboard() {
  const { user, loading: authLoading, logout } = useAuth();
  const [stats, setStats] = useState<LearningStats>({
    totalTopicsLearned: 0,
    totalQuestionsAnswered: 0,
    correctAnswers: 0,
    currentStreak: 0,
    totalStudyTime: 0,
  });
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    if (!authLoading) {
      if (!user) {
        router.push('/auth/login');
      } else {
        loadUserData();
      }
    }
  }, [user, authLoading, router]);

  async function loadUserData() {
    try {
      // 获取学习统计
      const response = await fetch('/api/stats/overview', {
        credentials: 'include',
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success && data.data) {
          setStats({
            totalTopicsLearned: data.data.topicsLearned || 0,
            totalQuestionsAnswered: data.data.totalQuestions || 0,
            correctAnswers: data.data.correctAnswers || 0,
            currentStreak: 0,
            totalStudyTime: data.data.totalTime || 0,
          });
        }
      }
    } catch (error) {
      console.error('加载用户数据失败:', error);
    } finally {
      setLoading(false);
    }
  }

  async function handleLogout() {
    await logout();
    router.push('/auth/login');
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="glassmorphism p-8 rounded-2xl">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  const accuracy = stats ? Math.round((stats.correctAnswers / stats.totalQuestionsAnswered) * 100) : 0;
  const studyHours = stats ? Math.floor(stats.totalStudyTime / 60) : 0;
  const studyMinutes = stats ? stats.totalStudyTime % 60 : 0;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism-nav sticky top-0 z-50 backdrop-blur-md bg-white/10 border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
                奥数学院
              </h1>
              {user && (
                <span className="text-sm text-gray-600">
                  欢迎回来，{user.username}！
                </span>
              )}
            </div>
            <div className="flex items-center space-x-4">
              {user?.role === 'admin' && (
                <button
                  onClick={() => router.push('/admin')}
                  className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                  title="管理员面板"
                >
                  <Shield className="w-5 h-5 text-purple-600" />
                </button>
              )}
              <button
                onClick={() => router.push('/profile')}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                title="个人设置"
              >
                <Settings className="w-5 h-5 text-gray-600" />
              </button>
              <button
                onClick={handleLogout}
                className="p-2 rounded-lg hover:bg-white/20 transition-colors"
                title="退出登录"
              >
                <LogOut className="w-5 h-5 text-gray-600" />
              </button>
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 欢迎区域 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glassmorphism p-6 rounded-2xl mb-8"
        >
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-3xl font-bold text-gray-800 mb-2">
                学习仪表板
              </h2>
              <p className="text-gray-600">
                {user && `${user.username} · 开始您的学习之旅`}
              </p>
            </div>
            <div className="text-right">
              <div className="text-2xl font-bold text-indigo-600">
                连续学习 {stats?.currentStreak || 0} 天
              </div>
              <div className="text-sm text-gray-500">保持下去！</div>
            </div>
          </div>
        </motion.div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600 mb-1">已学知识点</p>
                <p className="text-2xl font-bold text-indigo-600">
                  {stats?.totalTopicsLearned || 0}
                </p>
              </div>
              <BookOpen className="w-8 h-8 text-indigo-500" />
            </div>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600 mb-1">答题准确率</p>
                <p className="text-2xl font-bold text-green-600">
                  {accuracy}%
                </p>
              </div>
              <Target className="w-8 h-8 text-green-500" />
            </div>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600 mb-1">学习时长</p>
                <p className="text-2xl font-bold text-purple-600">
                  {studyHours}h {studyMinutes}m
                </p>
              </div>
              <Clock className="w-8 h-8 text-purple-500" />
            </div>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600 mb-1">总答题数</p>
                <p className="text-2xl font-bold text-orange-600">
                  {stats?.totalQuestionsAnswered || 0}
                </p>
              </div>
              <TrendingUp className="w-8 h-8 text-orange-500" />
            </div>
          </motion.div>
        </div>

        {/* 快速操作 */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 学习模式 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
              <BookOpen className="w-6 h-6 mr-2 text-indigo-500" />
              学习模式
            </h3>
            <div className="space-y-3">
              <button
                onClick={() => router.push('/learn')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800">知识点学习</div>
                    <div className="text-sm text-gray-600">系统化学习奥数知识</div>
                  </div>
                  <Play className="w-5 h-5 text-indigo-500" />
                </div>
              </button>
            </div>
          </motion.div>

          {/* 练习模式 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.6 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
              <Target className="w-6 h-6 mr-2 text-green-500" />
              练习模式
            </h3>
            <div className="space-y-3">
              <button
                onClick={() => router.push('/practice/daily')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800">每日练习</div>
                    <div className="text-sm text-gray-600">每天10道题巩固知识</div>
                  </div>
                  <Star className="w-5 h-5 text-yellow-500" />
                </div>
              </button>
              <button
                onClick={() => router.push('/practice/free')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800">自由练习</div>
                    <div className="text-sm text-gray-600">选择知识点自由练习</div>
                  </div>
                  <Play className="w-5 h-5 text-blue-500" />
                </div>
              </button>
              
              {/* 🔴 错题本按钮 - 测试可见性 */}
              <div style={{ background: 'red', padding: '10px', color: 'white', fontWeight: 'bold' }}>
                测试：这里应该有错题本按钮
              </div>
              
              <button
                onClick={() => router.push('/mistakes')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
                style={{ border: '3px solid red !important' }}
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800" style={{ color: 'red', fontSize: '20px' }}>🔴 错题本</div>
                    <div className="text-sm text-gray-600">复习错题，巩固知识</div>
                  </div>
                  <AlertCircle className="w-5 h-5 text-red-500" />
                </div>
              </button>
              
              <div style={{ background: 'green', padding: '10px', color: 'white', fontWeight: 'bold' }}>
                测试：错题本按钮已结束
              </div>
            </div>
          </motion.div>

          {/* 挑战模式 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.7 }}
            className="bg-white/80 backdrop-blur-sm p-6 rounded-2xl shadow-lg border border-gray-200/50"
          >
            <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
              <Trophy className="w-6 h-6 mr-2 text-yellow-500" />
              挑战模式
            </h3>
            <div className="space-y-3">
              <button
                onClick={() => router.push('/practice/challenge')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800">竞赛挑战</div>
                    <div className="text-sm text-gray-600">高难度竞赛级题目</div>
                  </div>
                  <Trophy className="w-5 h-5 text-yellow-500" />
                </div>
              </button>
              <button
                onClick={() => router.push('/reports')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800">学习报告</div>
                    <div className="text-sm text-gray-600">查看学习分析</div>
                  </div>
                  <TrendingUp className="w-5 h-5 text-green-500" />
                </div>
              </button>
              <button
                onClick={() => router.push('/social')}
                className="w-full glassmorphism-button p-4 rounded-xl text-left hover:scale-105 transition-transform"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-medium text-gray-800">社交中心</div>
                    <div className="text-sm text-gray-600">成就·排行榜</div>
                  </div>
                  <Star className="w-5 h-5 text-purple-500" />
                </div>
              </button>
            </div>
          </motion.div>
        </div>
      </div>
    </div>
  );
}

// Force update - ensure mistakes book entry is visible
